﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ML.Entity;
using ML.IRepository;
using Dapper;
using ML.Utils;

namespace ML.Repository
{
    public class CapitalAccountRepository : DBFactory, ICapitalAccountRepository
    {
        public Pager<CapitalAccountResponse> List(CapitalAccountSearch capitalAccountSearch)
        {
            var criteria = new PageCriteria() { TableName = "ml_capitalaccount ca INNER JOIN ml_merchant m on ca.MerchantId = m.Id" };
            if (!string.IsNullOrEmpty(capitalAccountSearch.name_search))
            {
                criteria.Conditions += string.Format(" AND m.Name LIKE'%{0}%'", capitalAccountSearch.name_search);
            }
            criteria.Conditions += string.Format(" AND ca.DelMark=0");

            criteria.PageIndex = capitalAccountSearch.pageindex;
            criteria.Field = @"m.Name,ca.*";
            criteria.PageSize = capitalAccountSearch.pagesize;
            criteria.SortName = capitalAccountSearch.ordername;
            if (capitalAccountSearch.orderby)
            {
                criteria.Sort = "DESC";
            }
            else
            {
                criteria.Sort = "ASC";
            }

            //调用存储过程进行查询并且返回
            var list = GetPageData<CapitalAccountResponse>(criteria);
            return list;
        }

        public IEnumerable<CapitalAccountEntity> GetCollectInfo(string merchantId)
        {
            string sql = @"SELECT * FROM ml_capitalaccount WHERE  DelMark = 0 ";
            if (!merchantId.Equals("-1"))
            {
                sql += " AND MerchantId=@MerchantId";
            }
            using (_db)
            {
                return _db.Query<CapitalAccountEntity>(sql, new { @MerchantId = merchantId });
            }
        }

        public CapitalAccountEntity GetByMerchantId(string id)
        {
            const string sql = @"SELECT * FROM ml_capitalaccount WHERE  DelMark = 0 AND MerchantId=@MerchantId";
            using (_db)
            {
                return _db.Query<CapitalAccountEntity>(sql, new { @MerchantId = id }).FirstOrDefault();
            }
        }

        public bool UpdateBalance(string id, decimal actPayPrice)
        {
            //首先查询商户汇总的信息
            const string update_capitalaccount = @"UPDATE ml_capitalaccount SET Balance=@Balance,UpdateTime=@UpdateTime WHERE MerchantId=@MerchantId";
            using (_db)
            {
                if (_db.Execute(update_capitalaccount, new { @Balance = actPayPrice, @MerchantId = id, @UpdateTime = DateTime.Now }) > 0)
                {
                    return true;
                }
                return false;
            }
        }
    }
}